<?php
namespace App\Task;

use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     rule="0 11 * * *",
 *     name="AutoGetBlog",
 *     callback="execute",
 *     memo="每2分钟处理博客",
 *     singleton=true
 * )
 */
class AutoGetBlog
{
    protected $logger;


    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('article', 'article');
    }

    public function execute()
    {
        $this->logger->info("====== 开始获取博客 ======");

        $databases = config('databases');
        $now = date('Y-m-d H:i:s');

        $webnames = array_filter(array_keys($databases), function($name) {
            return $name !== 'default';
        });

        foreach ($webnames as $webname) {
            try {
                $conn = Db::connection($webname);
                $limit = rand(5, 10);

                $total = $conn->selectOne("SELECT COUNT(*) as count FROM oc_blog WHERE status = 0");

                if ($total->count > 0) {
                    $offset = rand(0, max(0, $total->count - $limit));

                    $blogs = $conn->select("
                        SELECT blog_id FROM oc_blog 
                        WHERE status = 0 
                        LIMIT ? OFFSET ?
                    ", [$limit, $offset]);

                    foreach ($blogs as $blog) {
                        Db::connection('default')->insert("
                            INSERT INTO blogs_log (webname, blog_id, created_at)
                            VALUES (?, ?, ?)
                        ", [$webname, $blog->blog_id, $now]);
                    }

                    $this->logger->info("{$webname} 成功获取 " . count($blogs) . " 篇博客");
                }
            } catch (\Throwable $e) {
                $this->logger->error("{$webname} 获取博客失败：" . $e->getMessage());
            }
        }

        $this->logger->info("====== 博客获取结束 ======");
    }
}
